<?php

namespace app\admin\controller\school\course;

use app\admin\service\ReportService;
use app\BaseController;
use app\model\not_del\UserModel;
use app\model\school\SchoolCourseChapterCommentModel;
use app\model\school\SchoolCourseChapterLearningModel;
use app\model\school\SchoolCourseChapterModel;
use app\model\school\SchoolCourseModel;
use think\App;

class Index extends BaseController
{

    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    /**
     * 添加课程
     * @return bool|string
     */
    public function add(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'name|课程名称' => 'require',
                'editor|课程编写者' => 'require',
                'cover|封面图' => 'require',
                'introduce|课程总纲简介' => 'require',
                'is_comment|留言状态' => 'require|in:0,1',
                'status|启用状态' => 'require|in:0,1',
            ]);
            $param['unit_id'] = $this->userData['unit_id'];
            $param['time'] = time();
            $SchoolCourseModel = new SchoolCourseModel();
            $SchoolCourseModel->insert($param);
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 课程编辑
     * @return bool|string
     */
    public function update(): bool|string
    {
        $SchoolCourseModel = new SchoolCourseModel();
        $SchoolCourseModel->startTrans();
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require',
//                'chapter|章节' => 'require'
            ]);
            $info = $SchoolCourseModel->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            $SchoolCourseChapterModel = new SchoolCourseChapterModel();
            if (!empty($param['chapter'])) {
                $chapterData = [];
                foreach ($param['chapter'] as $v) {
                    if (empty($v['id'])){
                        if (isset($v['id'])){
                            unset($v['id']);
                        }
                        $v['unit_id'] = $this->userData['unit_id'];
                        $v['course_id'] = $param['id'];
                        $v['time'] = time();
                    }
                    $chapterData[] = $v;
                }
                $SchoolCourseChapterModel->saveAll($chapterData);
                $param['num'] = count($param['chapter']);
                unset($param['chapter']);
            }
            if (!empty($param['del'])) {
                $SchoolCourseChapterModel->where('id', 'in', $param['del'])->update([
                    'is_del' => 1,
                    'del_time' => time()
                ]);
                unset($param['del']);
            }
            $param['up_time'] = time();
            $info->save($param);
            $SchoolCourseModel->commit();
            return success();
        } catch (\Exception $e) {
            $SchoolCourseModel->rollback();
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 编辑者选择器
     * @return bool|string
     */
    public function editorSelector(): bool|string
    {
        try {
            $SchoolCourseModel = new SchoolCourseModel();
            $data = $SchoolCourseModel->where('unit_id', $this->userData['unit_id'])->distinct(true)->column('editor');
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 课程列表
     * @return bool|string
     */
    public function index(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'pageSize|每页显示数量' => 'require'
            ]);
            $where = [];
            $order = 'desc';
            $field = 'id';
            if (!empty($param['name'])) {
                $where[] = ['name', 'like', '%' . $param['name'] . '%'];
            }
            if (!empty($param['editor'])) {
                $where[] = ['editor', '=', $param['editor']];
            }
            if (isset($param['status']) && strlen($param['status']) > 0) {
                $where[] = ['status', '=', $param['status']];
            }
            if (!empty($param['collect_num'])){
                $field = 'collect_num';
                $order = $param['collect_num'];
            }
            if (!empty($param['study_num'])){
                $field = 'study_num';
                $order = $param['study_num'];
            }
            if (!empty($param['up_time'])){
                $field = 'up_time';
                $order = $param['up_time'];
            }
            $where[] = ['unit_id','=',$this->userData['unit_id']];
            $SchoolCourseModel = new SchoolCourseModel();
            $query = $SchoolCourseModel->where($where);
            $data = $query->order($field,$order)->paginate($param['pageSize'])->toArray();
            $data['ids'] = $query->column('id');
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 删除课程
     * @return bool|string
     */
    public function del(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require'
            ]);
            $SchoolCourseModel = new SchoolCourseModel();
            $SchoolCourseModel->where('id', 'in', $param['id'])->update([
                'is_del' => 1,
                'del_time' => time()
            ]);
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 修改状态
     * @return bool|string
     */
    public function status(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require',
                'status|状态' => 'require|in:0,1',
            ]);
            $SchoolCourseModel = new SchoolCourseModel();
            $SchoolCourseModel->where('id', 'in', $param['id'])->update([
                'status' => $param['status']
            ]);
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 课程详情
     * @return bool|string
     */
    public function info(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require'
            ]);
            $SchoolCourseModel = new SchoolCourseModel();
            $info = $SchoolCourseModel->with([
                'chapter' => function ($query) {
                    $query->with(['RatingScale']);
                }
            ])->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            return success($info);
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 学习情况列表
     * @return bool|string
     */
    public function LearningSituation(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require',
                'pageSize|每页显示数量' => 'require'
            ]);
            $where = [];
            $field = 'id';
            $order = 'desc';
            if (!empty($param['name'])){
                $UserModel = new UserModel();
                $uid = $UserModel->where('name|username','like','%'.$param['name'].'%')->column('id');
                if (!empty($uid)){
                    $where[] = ['uid','in',$uid];
                }else{
                    $where[] = ['id','=',-1];
                }
            }
            if (isset($param['is_finish']) && strlen($param['is_finish']) > 0) {
                $where[] = ['is_finish','=',$param['is_finish']];
            }
            if (isset($param['is_comment']) && strlen($param['is_comment']) > 0) {
                $where[] = ['is_comment','=',$param['is_comment']];
            }
            if (!empty($param['time'])){
                $field = 'time';
                $order = $param['time'];
            }
            $where[] = ['chapter_id','=',$param['id']];
            $SchoolCourseChapterLearningModel = new SchoolCourseChapterLearningModel();
            $data = $SchoolCourseChapterLearningModel->where($where)->with([
                'user',
                'result'
            ])->order($field,$order)->paginate($param['pageSize'])->toArray();
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 学习情况详情
     * @return bool|string
     */
    public function LearningSituationInfo(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require'
            ]);
            $SchoolCourseChapterLearningModel = new SchoolCourseChapterLearningModel();
            $userInfo = $SchoolCourseChapterLearningModel->with([
                'user',
                'result' => function ($query) {
                    $query->with(['ratingScaleName']);
                },
            ])->find($param['id']);
            if (!$userInfo) throw new \Exception('参数错误！');
            $SchoolCourseChapterModel = new SchoolCourseChapterModel();
            $chapterInfo = $SchoolCourseChapterModel->with([
                'chapterComment' => function ($query) {
                    $query->with(['user']);
                }
            ])->find($userInfo['chapter_id']);
            return success([
                'chapter' => $chapterInfo,
                'user' => $userInfo
            ]);
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 删除评论
     * @return bool|string
     */
    public function commentDel(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require'
            ]);
            $SchoolCourseChapterCommentModel = new SchoolCourseChapterCommentModel();
            $info = $SchoolCourseChapterCommentModel->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            $info->save([
                'is_del' => 1,
                'del_time' => time()
            ]);
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 删除学习记录
     * @return bool|string
     */
    public function learningDel(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require'
            ]);
            $SchoolCourseChapterLearningModel = new SchoolCourseChapterLearningModel();
            $SchoolCourseChapterLearningModel->where('id', 'in', $param['id'])->update([
                'is_del' => 1,
                'del_time' => time()
            ]);
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 结果详情
     * @return bool|string
     */
    public function reportInfo(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require',
            ]);
            $ReportService = new ReportService($this->app);
            $data = $ReportService->getSchoolEvaluationReportInfo($param['id']);
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }
}